function loadImage(url,code,callback){
    cc.loader.load(url,function (err,tex) {
        // 电脑登录的userid拿不到头像
        if (!tex) {
            return
        };
        var spriteFrame = new cc.SpriteFrame(tex, cc.Rect(0, 0, tex.width, tex.height));
        callback(code,spriteFrame)
    })
};

function getBaseInfo(userid,callback){
    cc.vv.http.sendRequest('/base_info',{userid:userid},function(ret){
        // console.log("base_info/ret",ret);
        var url = null;
        if(ret.headimgurl){
           url = ret.headimgurl + ".jpg"
        };
        var info = {
            name:ret.name,
            sex:ret.sex,
            url:url
        };
        callback(userid,info)
    },cc.vv.http.master_url)
};

cc.Class({
    extends: cc.Component,
    properties: {
        // foo: {
        //    default: null,      // The default value will be used only when the component attaching
        //                           to a node for the first time
        //    url: cc.Texture2D,  // optional, default is typeof default
        //    serializable: true, // optional, default is true
        //    visible: true,      // optional, default is true
        //    displayName: 'Foo', // optional
        //    readonly: false,    // optional, default is false
        // },
        // ...
    },

    // use this for initialization
    onLoad: function () {
        this.setupSpriteFrame()
    },
    
    setUserID:function(userid){
        // if(cc.sys.isNative == false){
        //     return
        // };
        if(!userid){
            return
        };
        // 保存头像
        if(cc.vv.icons == null){
            cc.vv.icons = {};
        };
        var self = this;
        // 本地有头像直接拿，没有则获取
        if (cc.vv.icons[userid]) {
            console.log("本地已经有这个用户头像",userid);
            var spr = this.getComponent(cc.Sprite);
            if(spr){
                spr.spriteFrame = cc.vv.icons[userid];    
            }
        }else{
            console.log("本地没有这个用户头像",userid);
            getBaseInfo(userid,function(code,info){
               if(info && info.url){
                    loadImage(info.url,userid,function (err,spriteFrame) {
                        self._spriteFrame = spriteFrame;
                        // 保存头像
                        cc.vv.icons[userid]=spriteFrame;
                        self.setupSpriteFrame();
                    });   
                } 
            })
        }
    },
    
    setupSpriteFrame:function(){
        if(this._spriteFrame&&this!=null){
            var spr = this.getComponent(cc.Sprite);
            if(spr){
                spr.spriteFrame = this._spriteFrame  
            }
        }
    }
    // called every frame, uncomment this function to activate update callback
    // update: function (dt) {

    // },
});
